﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using PloobsEngine.Utils;
using PloobsEngine;

namespace Etapa1.SteeringExperiments
{
    public class Wander : Steering
    {
        public Wander(double refreshRate, float distanciaCirculo, float raioCirculo, float decelerationBeginsAtDistance,Deceleration deceleration )
            : base(BehaviorType.wander)
        {
            _arrive = new Arrive(_target, deceleration, decelerationBeginsAtDistance);
            this._refreshRate = refreshRate;
            this._distanciaCirculo = distanciaCirculo;
            this._radioCirculo = raioCirculo;
        }
        
        private Vector3 _target;
        private double _time = 0.0d;

        private double _refreshRate;
        private Arrive _arrive;
        private float _distanciaCirculo;
        private float _radioCirculo;
        private const float MINIMUM_DISTANCE = 10.0f;

        public Vector3 Target
        {
            get
            {
                return _target;
            }
            set
            {
                this._target = value;
                this._arrive.Target = value;
            }
        }


        public override Microsoft.Xna.Framework.Vector3 CalculateSteering(SteeringEntityInfo entity)
        {            
            _time +=  EngineStuff.GetCurrentGameTime().ElapsedGameTime.TotalMilliseconds;

            if (_time == 0.0d || _time >= _refreshRate || Vector3.Distance(entity.Obj.Position, Target) <= MINIMUM_DISTANCE)
            {
                _time = 0.1d;

                float anguloTMP = StaticRandom.RandomIntInterval(-360, 360);

                // Buscamos una posición aleatoria en el círculo
                float posicionXCirculo = entity.Obj.Position.X + _distanciaCirculo + ((float)Math.Cos(anguloTMP) * _radioCirculo);
                float posicionYCirculo = entity.Obj.Position.Z + _distanciaCirculo + ((float)Math.Sin(anguloTMP) * _radioCirculo);

                // Ahora se comporta como un steering de arrive, previo establecimiento del target calculado
                _arrive.Target = new Vector3(posicionXCirculo,0 ,posicionYCirculo);
                this.Target = _arrive.Target;
            }

            return _arrive.CalculateSteering(entity);

        }
    }
}
